package com.zyt.interceptor;

import com.zyt.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
/*
*令牌校验的拦截器
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //2.获取请求路径
        String requestURI = request.getRequestURI();

        //3.判断是否为登录请求,如果是登录请求,则放行
        if (requestURI.contains("login")) {
            log.info("登录请求,放行");

            return true;
        }
        //4.获取请求头中的token
        String token = request.getHeader("token");

        //5.判断是否有 token,如果无token,则拦截,返回状态码:401
        if (token == null || token.isEmpty()) {
            log.info("令牌为空,拦截");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //6.解析token,如果解析失败,则拦截,返回状态码:401
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            log.info("令牌非法,拦截");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return  false;
        }

        //7.解析成功,则放行
        log.info("令牌解析成功,放行");
        return true;
    }
}

